#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2008-08-15.
# $Id$
#

import logging

from django.template import loader, Context
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseNotFound

from buggarden.foodsnroses.views import view_utils


#---------------------------------------------------------------------------------------------------

def not_found(request):
    """Returns the 404 not-found page."""
    
    ctxt_dict = {'url': request.path,}
    ctxt = view_utils.create_context(request, ctxt_dict)
    tmpl = view_utils.get_template('not_found.html')
    return HttpResponseNotFound(tmpl.render(ctxt))

#---------------------------------------------------------------------------------------------------

def error(request, message=None):
    """Returns the error page."""
    
    if message:
        prompt = view_utils.Prompt.create_error(message)
    else:
        prompt = view_utils.Prompt(request.REQUEST)
    ctxt_dict = {'prompt': prompt,}
    ctxt = view_utils.create_context(request, ctxt_dict)
    tmpl = view_utils.get_template('error.html')
    return HttpResponse(tmpl.render(ctxt))

#---------------------------------------------------------------------------------------------------

def _get_pretty_name(name):
    SPECIAL_PRETTY_NAMES = {
        'faq': 'Frequently asked questions',
        'history_n_future': "History n' future",
    }
    default_pretty_name = ' '.join(name.split('_')).capitalize()
    return SPECIAL_PRETTY_NAMES.get(name, default_pretty_name)

class DocumentPath(object):
    """This class represents a path to a document. Its instance has the following attributes:
    - path: the path to the document (without the ending slash).
    - pretty_name: the pretty name of the document, generated from the last entry of the path.
    - parents: a list of 2-tuple providing a navigation from root to the current document,
               first value is the path, second value is the pretty name.
    """
    
    def __init__(self, path_entries):
        assert len(path_entries) > 0, 'Path entries should not be empty.'
        self.path = '/'.join(path_entries)
        self.pretty_name = _get_pretty_name(path_entries[-1])
        self.parents = []
        for i in range(1, len(path_entries)):
            path = '/'.join(path_entries[0:i])
            pretty_name = _get_pretty_name(path_entries[i - 1])
            self.parents.append((path, pretty_name))

def document(request, path):
    """Returns the document page specified by path."""
    
    try:
        doc_path = DocumentPath(path.split('/'))
        ctxt = view_utils.create_context(request, {'doc_path': doc_path,})
        tmpl = view_utils.get_template('doc/%s.html' % path)
        return HttpResponse(tmpl.render(ctxt))
    except Exception, exc:
        logging.warning('Failed to serve document "%s": %s' % (path, str(exc)))
        return not_found(request)

#---------------------------------------------------------------------------------------------------




